﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SimpleBoard.Trigger
{
    [XmlInclude(typeof(BoolFilter))]
    [XmlInclude(typeof(FloatFilter))]
    [XmlInclude(typeof(IntegerFilter))]
    [XmlInclude(typeof(StringFilter))]
    [XmlInclude(typeof(ToggleFilter))]
    public class Trigger
    {
        /// <summary>
        /// 触发器名称
        /// </summary>
        public string Name { get; set; } = null!;
        /// <summary>
        /// 触发器类型
        /// </summary>
        public string TargetType { get; set; } = null!; // device/form

        /// <summary>
        /// 对象ID
        /// </summary>
        public Guid TargetId { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; }

        /// <summary>
        /// 是否处于激活状态
        /// </summary>
        public bool IsActivated { get; set; }

        /// <summary>
        /// 持续激活时的触发间隔
        /// </summary>
        public int Interval { get; set; }

        /// <summary>
        /// 触发时执行的操作
        /// </summary>
        public string Action { get; set; } = null!;

        /// <summary>
        /// 操作参数列表
        /// </summary>
        public string[] ActionParameters { get; set; } = null!;

        /// <summary>
        /// 条件过滤器组
        /// </summary>
        public Filter[] Filters { get; set; } = null!;

        /// <summary>
        /// 判断值是否满足过滤条件
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool IsFitConditions(object value)
        {
            var execute = true;
            foreach (var filter in Filters)
            {
                execute &= filter.IsFitCondition(value);
            }
            return execute;
        }

        private object? cachedValue;

        /// <summary>
        /// 使用缓存的值判断是否满足过滤条件
        /// </summary>
        /// <returns></returns>
        public bool IsFitConditions()
        {
            if (cachedValue is null) return false;
            var execute = true;
            foreach (var filter in Filters)
            {
                execute &= filter.IsFitCondition(cachedValue);
            }
            return execute;
        }
    }
}
